package controller;
import pojo.Cart;
import pojo.CartItem;
import pojo.Product;
import pojo.User;
import service.ProductService;
import service.impl.ProductServiceimpl;

import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author LiangHaiBo
 * @version 1.0
 * @date 2021.9.9 下午 14:35
 */

@WebServlet("/cart")
public class CartServlet extends BaseServlet {

    /**
     * 获取购物车(无论添加购物车项还是删除购物车项还是清空购物车)
     */
    public Cart getCart(HttpServletRequest request){
        Cart cart = (Cart) request.getSession().getAttribute("cart");
        if(cart == null){
            cart = new Cart();
            request.getSession().setAttribute("cart",cart);
        }
        return  cart;
    }

    /**
     * 加入购物车
     */
    public  String add(HttpServletRequest request, HttpServletResponse response) throws IOException {
        //从session域中获取user,如果user==null,跳转登录
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if(user == null){
            //说明没有登陆
            return "/jsp/login.jsp";
        }

        //接收参数,获取商品编号
        String pid = request.getParameter("pid");
        //获取商品数量
        String i = request.getParameter("count");
        int count = Integer.parseInt(i);
        //通过商品id获取商品实体
        //调用商品的业务接口
        ProductService productService = new ProductServiceimpl();
        Product product = productService.getProductById(pid);

        //封装购物车项的数据
        CartItem cartItem = new CartItem(product,count);

        //获取购物车
        Cart cart = getCart(request);

        cart.addCartItemToCart(cartItem);

        response.sendRedirect(request.getContextPath()+"/jsp/cart.jsp");
        return null;
    }

    /**
     * 将购物车项从购物车中删除
     * @param request
     * @param response
     */
    public  void removeCartItemFromCart(HttpServletRequest request,HttpServletResponse response) throws IOException {
        String pid = request.getParameter("pid");

        Cart cart = getCart(request);

        cart.deleteCartItemFromCart(pid);

        response.sendRedirect(request.getContextPath()+"/jsp/cart.jsp");
    }

    /**
     * 暴力清空购物车
     * @param request
     * @param response
     */
    public  void clear(HttpServletRequest request,HttpServletResponse response) throws IOException {
        Cart cart = getCart(request);
        cart.clearCart();

        request.getSession().removeAttribute("cart");

        response.sendRedirect(request.getContextPath()+"/jsp/cart.jsp");
    }

}
